<template>
  <div class="login-container">
    <div class="login-form" style="background-color: #02e0ff; padding-top: 50px;">
      <img src="../assets/logo1.png" alt="Logo" class="logo" />
      <h1>我与软件有个约会</h1>
      <h2>评分系统</h2>
      <form @submit.prevent="handleLogin">
        <label for="judUsername">请输入账号/工号</label>
        <input type="text" id="judUsername" v-model="form.judUsername" required />
        <label for="judPassword">请输入密码</label>
        <input type="judPassword" id="judPassword" v-model="form.judPassword" required />
        <button type="submit" class="login-button" @click="login()" :disabled="this.loading">{{ this.loginText
          }}</button>
      </form>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      form: {},
      token: '',
      Role: '',
      loading: false,
      loginText: "登录"
    };

  },
  methods: {
    async login() {
      this.loading = true;
      this.loginText = "登录中"
      let countdown = 3; // 倒计时时间（秒）
      let countdownInterval;
      //base64加密

      // 创建一个Promise来处理登录逻辑
      const loginPromise = new Promise((resolve, reject) => {
        if (this.form.judUsername === undefined || this.form.judPassword === undefined) {
          this.$message({
            message: '用户名和密码不能为空，请重新输入',
            type: 'error'
          });
          resolve(false); // 立即结束
          return;
        }

        let encodedForm = {};
        encodedForm.judUsername = btoa(this.form.judUsername);
        encodedForm.judPassword = btoa(this.form.judPassword);
        request.post("/judge/login", encodedForm)
          .then(res => {
            console.log("res:", res);
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: 'error'
              });
              resolve(false); // 登录失败
            } else {
              this.token = res.data.token;
              this.Role = res.data.judRole;
              if (res.code === 1 && this.Role == '0') {
                this.$message({
                  message: '登录成功，欢迎使用管理员系统！',
                  type: 'success'
                });
                localStorage.setItem("user", JSON.stringify(res.data));
                this.$router.push('/layout');
                resolve(true); // 登录成功
              } else if (res.code === 1 && this.Role == '1') {
                this.$message({
                  message: '登录成功，欢迎使用评委系统！',
                  type: 'success'
                });
                localStorage.setItem("user", JSON.stringify(res.data));
                window.location.href = "/PwYeMian/judger.html";
                resolve(true); // 登录成功
              } else {
                this.$message({
                  message: '用户名或密码错误请重新输入！',
                  type: 'error'
                });
                resolve(false); // 登录失败
              }
            }
          })
          .catch(error => {
            this.$message({
              message: '登录请求失败，请稍后再试。',
              type: 'error'
            });
            console.error('Login request failed:', error);
            resolve(false); // 登录失败
          });
      });

      const startCountdown = () => {
        countdownInterval = setInterval(() => {
          if (countdown > 0) {
            this.loginText = `登录失败 (${countdown}s)`;
            countdown--;
          } else {
            clearInterval(countdownInterval);
            this.loginText = '登录';
            this.loading = false;
          }
        }, 1000);
      };

      // 等待登录Promise完成
      const result = await loginPromise;

      // 如果登录失败，启动3秒倒计时
      if (!result) {
        countdown = 3;
        // this.loginText = `登录失败，请稍后再试... (${countdown}s)`;
        startCountdown();
      } else {
        // 登录成功，立即停止倒计时
        if (countdownInterval) {
          clearInterval(countdownInterval);
        }
        this.loading = false;
      }
    },
    handleLogin() {
      this.login();
    },
    showAlert(message) {
      alert(message); // 使用浏览器的alert弹窗显示消息
    }
  }
};
</script>

<style scoped>
/* Reset some basic styles */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Arial', sans-serif;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #ffcc99, #ff9966), url()no-repeat center center fixed;
  background-size: cover;
  background-color: #ffcc99;
  /* Fallback color */
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  position: relative;
}

.login-form {
  background: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  text-align: center;
  max-width: 400px;
  width: 100%;
  position: relative;
  overflow: hidden;
  padding-top: 50px;
}

.logo {
  width: 100px;
  margin-bottom: 20px;
  animation: bounce 2s infinite;
}

.login-form h1 {
  font-size: 2em;
  margin-bottom: 10px;
  color: white;
}

.login-form h2 {
  font-size: 1.5em;
  margin-bottom: 30px;
  color: white;
}

.login-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: white;
}

.login-form input[type="text"],
.login-form input[type="judPassword"] {
  width: 100%;
  padding: 10px;
  margin-bottom: 15px;
  border: none;
  border-radius: 5px;
  outline: none;
  transition: all 0.3s ease-in-out;
  background: rgba(255, 255, 255, 0.8);
  color: #ff6600;
}

.login-form input[type="text"]:focus,
.login-form input[type="judPassword"]:focus {
  box-shadow: 0 0 5px rgba(255, 102, 0, 1);
}

.login-button {
  padding: 10px 20px;
  background-color: #ff6600;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  margin: 0 auto;
  display: block;
  box-shadow: 0 0 10px rgba(255, 102, 0, 0.5);
}

.login-button:hover {
  background-color: #ff9966;
  box-shadow: 0 0 20px rgba(255, 102, 0, 1);
}

/* Animation */
@keyframes bounce {

  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }

  40% {
    transform: translateY(-20px);
  }

  60% {
    transform: translateY(-10px);
  }
}

/* Media queries for responsiveness */
@media (max-width: 600px) {
  .login-form {
    padding: 20px;
  }

  .logo {
    width: 80px;
  }

  .login-form h1 {
    font-size: 1.5em;
  }

  .login-form h2 {
    font-size: 1.2em;
  }
}
</style>
